﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// DB 的摘要说明
/// 数据库连接的基本操作
/// 只能执行单条语句
/// SqlDataAdapter获取数据
/// </summary>

namespace SQLHelper
{
    public class DB
    {
        // 数据库连接字符串
        private static string ConnectionString = "Server=.;Initial Catalog=noap;trusted_connection=true";

        // 数据库连接对象
        private static SqlConnection SqlCon = null;

        // 返回搜索结果 - SqlDataReader
        public static SqlDataReader GetDataWithQuery(string str)
        {
            SqlCon = new SqlConnection(ConnectionString);
            SqlCommand SqlCom = new SqlCommand(str, SqlCon);
            SqlCon.Open();
            SqlDataReader res = SqlCom.ExecuteReader();
            try
            {
                return res;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DisponseSqlCom(SqlCom);
            }
        }

        // 返回搜索结果 - SqlDataAdapter - DataSet
        public static DataSet GetDataWithQuerySecond(string str, string table)
        {
            SqlCon = new SqlConnection(ConnectionString);
            SqlDataAdapter SqlData = new SqlDataAdapter(str, SqlCon);
            DataSet res = new DataSet();
            SqlCon.Open();
            SqlData.Fill(res, table);
            try
            {
                return res;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DisponseSqlData(SqlData);
            }
        }

        // 只执行不返回结果
        public static void GetDataNoQuery(string str)
        {
            SqlCon = new SqlConnection(ConnectionString);
            SqlCommand SqlCom = new SqlCommand(str, SqlCon);
            SqlCon.Open();
            try
            {
                SqlCom.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DisponseSqlCom(SqlCom);
            }
        }

        // 关闭数据库
        public static void ColseSqlCon()
        {
            if (SqlCon != null)
            {
                SqlCon.Close();
            }
        }

        // 释放资源
        public static void DisponseSqlCom(SqlCommand SqlCom)
        {
            if(SqlCom != null)
            {
                SqlCom.Dispose();
                SqlCom = null;
            }
        }

        // 释放资源 - 2
        public static void DisponseSqlData(SqlDataAdapter SqlData)
        {
            if (SqlData != null)
            {
                SqlData.Dispose();
                SqlData = null;
            }
        }

        public DB()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
    }
}
